package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex((password + "itheima").getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void editPassword(PasswordEditDTO dto) {
        // 查看旧密码是否正确
        Employee employee = employeeMapper.getByIdPassword(dto);
        if(null == employee)
            throw new RuntimeException("此员工旧密码不匹配");
        // 获取当前修改人
        employee.setUpdateUser(BaseContext.getCurrentId());
        // 获取当前修改时间
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateById(employee);
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
//        账号必须是唯一的
        Employee employee = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (null != employee)
            throw new RuntimeException("已存在此用户名");
        employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
//        记得插入修改人和创建人，修改时间创建时间
        Long currentId = BaseContext.getCurrentId();
        employee.setCreateUser(currentId);
        employee.setUpdateUser(currentId);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
//        dto没密码参数，密码默认为123456
//        以后密码需要加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456itheima".getBytes()));
//        dto没状态参数，默认正常状态 1
        employee.setStatus(1);
        employeeMapper.save(employee);
    }

    @Override
    @Validated
    public PageResult page(EmployeePageQueryDTO dto) {
//          除了分页条件以外，还有一个查询条件 "员工姓名"
//          根据页码展示员工信息
//          每页展示10条数据
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
//          分页查询时可以根据需要，输入员工姓名进行查询
//          返回数据中records数组中使用Employee PageResult
        Page<Employee> page = employeeMapper.page(dto);
        return new PageResult(page.getTotal() ,page.getResult());
    }

    @Override
    public void status(int status, long id) {
//        没有修改人和修改时间参数，自己添加
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.updateById(employee);
    }

    @Override
    public Employee getOne(long parseLong) {
//        根据id查询员工信息
        Employee employee = employeeMapper.getById(parseLong);
//        查询员工为null，抛异常
        if(null == employee)
            throw new RuntimeException("查无此员工...");
    return employee;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        // 参数没有修改人id和修改时间，手动填写
        Employee build = Employee.builder()
                .build();
        BeanUtils.copyProperties(employeeDTO, build);
        employeeMapper.updateById(build);
    }

}
